package com.getpebble.android.framework.discovery;

import android.content.ContentResolver;
import android.content.Context;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.common.core.trace.Analytics.RemoteDeviceInterface;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.model.PblDevice;
import com.getpebble.android.common.model.PblDeviceModel;
import com.getpebble.android.framework.DeviceInterfaces.IDeviceFetcher;
import com.getpebble.android.framework.DeviceInterfaces.IDeviceFetcherCallback;
import java.util.Set;

public class DiscoveryManager implements IDeviceFetcherCallback {
    private static final String TAG = DiscoveryManager.class.getSimpleName();
    private final IDeviceFetcher mDeviceFetcher;

    public DiscoveryManager(Context context, IDeviceFetcher deviceFetcher) {
        if (context == null) {
            throw new IllegalArgumentException("context null");
        } else if (deviceFetcher == null) {
            throw new IllegalArgumentException("deviceFetcher null");
        } else {
            this.mDeviceFetcher = deviceFetcher;
            PblDeviceModel.purgeUnknownDevices(context.getContentResolver());
            getBondedDevices();
            this.mDeviceFetcher.registerBluetoothDevicesCallback(this);
        }
    }

    private Context getContext() {
        return PebbleApplication.getAppContext();
    }

    public void getBondedDevices() {
        Context context = getContext();
        if (context == null) {
            Trace.warning(TAG, "getBondedDevices(): context is null");
            return;
        }
        Set<PblDevice> devices = this.mDeviceFetcher.getBondedPblDevices();
        ContentResolver contentResolver = context.getContentResolver();
        for (PblDevice device : devices) {
            PblDeviceModel.insert(contentResolver, device);
        }
    }

    public void onDeviceBonded(PblDevice device) {
    }

    public void onDeviceUnbonded(PblDevice device) {
    }

    public void onDeviceDiscovered(PblDevice device) {
        Context context = getContext();
        if (context == null) {
            throw new IllegalArgumentException("context null");
        }
        PblDeviceModel.insert(context.getContentResolver(), device);
        RemoteDeviceInterface.logRemoteDeviceDiscovered(device.getAddress());
    }

    public void destroy() {
        this.mDeviceFetcher.unregisterBluetoothDevicesCallback(this);
    }
}
